import frappe
from frappe.database.db_manager import DbManager
from frappe import _

class DmDbManager(DbManager):
    def __init__(self, db):
        super().__init__(db)

    def get_current_host(self):
        # 达梦不需要host概念，返回空字符串
        return ""

    def create_user(self, user, password, host=None):
        # 达梦创建用户的SQL语法 - 使用双引号包裹密码，并对密码中的特殊字符进行转义
        escaped_password = password.replace('"', '""')
        #print(f'CREATE USER {user} IDENTIFIED BY "{escaped_password}"')
        self.db.sql(f'CREATE USER {user} IDENTIFIED BY "{escaped_password}"')
        
    def delete_user(self, target, host=None):
        # 达梦删除用户的SQL语法
        #print(f"DROP USER IF EXISTS {target} CASCADE")
        self.db.sql(f"DROP USER IF EXISTS {target} CASCADE")

    def create_database(self, target):
        """
        在达梦中创建数据库实际上是创建表空间
        """
        # 首先创建表空间文件目录
        tablespace_path = f"/opt/dmdbms/data/{target}"
        self.db.sql(f"""
            CREATE TABLESPACE {target} 
            DATAFILE '{tablespace_path}.dbf' 
            SIZE 32 
            AUTOEXTEND ON NEXT 32
        """)
        
        # 设置默认表空间
        self.db.sql(f"ALTER USER {target} DEFAULT TABLESPACE {target}")

    def drop_database(self, target):
        """删除数据库（表空间）"""
        # 首先检查表空间是否存在
        exists = self.db.sql("""
            SELECT COUNT(*) 
            FROM DBA_TABLESPACES 
            WHERE TABLESPACE_NAME = :1
        """, (target.upper(),))[0][0]
        
        if exists:
            self.db.sql(f"DROP TABLESPACE {target.upper()}")

    def grant_all_privileges(self, target, user, host=None):
        """
        授予达梦用户权限
        """
        self.db.sql(f"GRANT DBA TO {user}")
        self.db.sql(f"GRANT RESOURCE TO {user}")

    def get_database_list(self):
        """
        获取所有表空间列表
        """
        
        return self.db.sql("SELECT TABLESPACE_NAME FROM DBA_TABLESPACES")

    @staticmethod
    def restore_database(verbose, source_sql=None):
        """
        从SQL文件恢复数据库
        """
        if verbose:
            print("Starting database restore...")

        # 读取SQL文件内容
        with open(source_sql, 'r') as f:
            sql_content = f.read()
            
        # 执行SQL语句
        for statement in sql_content.split(';'):
            if statement.strip():
                frappe.db.sql(statement)
                if verbose:
                    print(f"Executed: {statement[:50]}...") 